package com.jbp.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.jbp.exception.RRException;
import com.jbp.model.*;
import com.jbp.service.*;
import com.jbp.utils.R;
import com.jbp.utils.StrToMillsUtil;
import io.swagger.models.auth.In;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;

import com.jbp.dao.RoomDao;
import org.springframework.transaction.annotation.Transactional;


@Service
public class RoomServiceImpl extends ServiceImpl<RoomDao, Room> implements RoomService {


    @Autowired
    private RoomUserWheatService roomUserWheatService;

    @Autowired
    private RoomWheatService roomWheatService;

    @Autowired
    private RoomBlockService roomBlockService;

    @Autowired
    private RoomCollectService roomCollectService;

    @Autowired
    private UserService userService;

    @Autowired
    private RoomManagerService roomManagerService;

    @Autowired
    private RoomTagService roomTagService;

    @Autowired
    private RoomRecomendService roomRecomendService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<Room> queryWrapper=new QueryWrapper<>();
        if (params.get("name") != null && !params.get("name").equals("")){
            queryWrapper.like("name",params.get("name")).or().like("uuid",params.get("name"));
        } else {
            queryWrapper.eq("status", "normal");
        }
        if (params.get("typeId") != null && params.get("typeId").equals("0")){
            //推荐列表
            queryWrapper.eq("is_push",1);
            //不显示加密房间
            queryWrapper.ne("encryption", 1);
            //不取pin房间
            queryWrapper.eq("pin", -1);
            //娱乐厅在最后面
            queryWrapper.orderByAsc("type_id=2");
        } else if (params.get("typeId") != null && !params.get("typeId").equals("0")){
            //加密厅在最后面
            queryWrapper.orderByAsc("encryption=1");
        }
        if(params.get("typeId") != null && !params.get("typeId").equals("0") && !params.get("typeId").equals("-1")){
            queryWrapper.eq("type_id",params.get("typeId"));
        }
        queryWrapper.notInSql("id", "SELECT room_id FROM room_recomend");
        if (params.get("typeId") != null && params.get("typeId").equals("-1")){
            List<Integer> ids=roomCollectService.getRoomIds(Integer.parseInt(params.get("userId").toString()));
            if (ids == null ||  ids.size() < 1){
               queryWrapper.eq("id",0);
            }else{
                queryWrapper.in("id",ids);
            }
        }
        if (params.get("typeId") != null && params.get("typeId").equals("7")) {
            queryWrapper.ne("people_mood", 0);
        }

        //根据人气值排序（倒序）
        queryWrapper.orderByDesc("mood+fixation_mood+people_mood");
        IPage<Room> page = this.page(
                new Query<Room>().getPage(params),
                queryWrapper
        );

        //推荐列表  要加固定房间
        if (page.getCurrent()==1 && page.getRecords()!=null && params.get("typeId") != null && params.get("typeId").equals("0")){
            QueryWrapper<Room> queryWrapperPin = new QueryWrapper<Room>().ne("pin", -1).orderByAsc("pin");
            List<Room> pinlist = list(queryWrapperPin);
            for (Room roomPin : pinlist) {
                if (roomPin.getPin()<page.getRecords().size()) {
                    page.getRecords().add(roomPin.getPin(), roomPin);
                }
            }
        }
        Integer userId = (Integer)params.get("userId");

        page.getRecords().forEach( li -> {
           fomartMainRoom(li, userId);
        });
        return new PageUtils(page);
    }

    private void fomartMainRoom(Room li, Integer userId) {
        User user =userService.getById(li.getUserId());
        if (user != null){
            li.setImg(user.getImg());
        }
        li.setMood(li.getMood()+li.getFixationMood()+li.getPeopleMood());
        //查询是否在收藏列表
        RoomCollect collect= roomCollectService.getOne(new QueryWrapper<RoomCollect>().eq("user_id", userId).eq("room_id",li.getId()));
        if (collect != null){
            li.setIsCollect("yes");
        }

        //设置主持人
        List<RoomUserWheat>  userWheats=roomUserWheatService.list(new QueryWrapper<RoomUserWheat>().eq("room_id",li.getId()).eq("room_wheat",1));
        if (userWheats!=null) {
            userWheats.forEach(userWheat->{
                User zc = userService.getById(userWheat.getUserId());
                userWheat.setUserName(zc.getName());
                userWheat.setUserImg(zc.getImg());
                userWheat.setUserSex(zc.getSex());
            });
        }
        li.setUserWheats(userWheats);

        //用户是否是房间的房主或者管理
        if (userId.intValue()==li.getUserId().intValue()) {
            li.setRole("master");
        } else {
            RoomManager roomManager = roomManagerService.getOne(new QueryWrapper<RoomManager>()
                    .eq("room_id", li.getId())
                    .eq("user_id", userId));
            if (roomManager!=null) {
                li.setRole("manager");
            }
        }

        //标签
        if (li.getTagId()!=null) {
            RoomTag roomTag = roomTagService.getById(li.getTagId());
            if (roomTag!=null) {
                li.setTagImage(roomTag.getImage());
            }
        }
    }

    //推荐房间列表
    @Override
    public List<Room> recommendRooms(Integer userId){
        List<Room> rooms = getBaseMapper().getRecommendRooms();
        for (Room room : rooms) {
            fomartMainRoom(room, userId);
        }
        return rooms;
    }

    /**
     * 进入房间
     * @param req
     */
    @Override
    @Transactional
    public synchronized void inRoom(Room req) {
        Room rom=this.getById(req.getId());
        if (rom == null){
            throw new RRException("房间号不存在");
        }
        /**
         * 查看是否黑名单成员
         */
       RoomBlock block= roomBlockService.getOne(new QueryWrapper<RoomBlock>().eq("user_id",req.getUserId()).eq("room_id",rom.getId()));
       if (block != null){
           throw new RRException("您已拉入禁入黑名单");
       }
       //查询是否已存在房间
//        RoomUserWheat userWheat=  roomUserWheatService.getOne();
        roomUserWheatService.remove(new QueryWrapper<RoomUserWheat>().eq("user_id",req.getUserId()));
       /*if (userWheat != null){
            //进入的新房间是否与原房间不一样 不一样则修改
            if (!userWheat.getRoomId().equals(req.getId())){
                Room rm=this.getById(userWheat.getRoomId());
                rm.setPeopleMood(rm.getPeopleMood()-50);
                //退出原房间
                this.updateById(rom);
                roomUserWheatService.removeById(userWheat.getId());
            }
        }*/
//        if (rom.getEncryption().equals("1")){
//            if (StringUtils.isEmpty(room.getPassword())){
//                throw new RRException("请输入房间密码");
//            }
//            if (!StrToMillsUtil.passwordEncode(room.getPassword(),"aaa").equals(rom
//                    .getPassword())){
//                throw new RRException("密码错误");
//            }
//        }

        //进入新房间  新房间是否自己创建的房间
        RoomUserWheat userWheat=new RoomUserWheat();
        userWheat.setCreateTime(new Date());
        userWheat.setUserId(req.getUserId());
        userWheat.setRoomId(rom.getId());
        userWheat.setStatus("online");
        //如果进入的房间是自己创建的房间
        if (rom.getUserId().equals(req.getUserId())){
            userWheat.setRoomWheat(0);
            userWheat.setType("house");
            //更新麦位进入时间
            /*RoomWheat roomWheat=roomWheatService.getOne(new QueryWrapper<RoomWheat>().eq("user_id",room.getUserId()).eq("place",0));
            roomWheat.setOnRoomTime(new Date());
            roomWheatService.updateById(roomWheat);*/
        }else {
            userWheat.setType("common");
        }
        //进入房间房间人气值加50
        rom.setPeopleMood(rom.getPeopleMood()+ userService.getPeopleMood(userWheat.getUserId()));
        this.updateById(rom);

        User user = userService.getById(req.getUserId());
        user.setIsOnline("inroom");
        userService.updateById(user);

        roomUserWheatService.save(userWheat);
    }


    /**
     * 清楚心动值
     * @param roomId 房间Id
     */
    @Override
    public void clearCharm(Integer roomId) {
        List<RoomWheat> roomWheat = roomWheatService.list(new QueryWrapper<RoomWheat>().eq("room_id",roomId));
        if (roomWheat == null){
            throw new RRException("房间信息错误");
        }
        roomWheat.forEach(list -> {
            list.setCharm(0);
            roomWheatService.updateById(list);
        });
    }

    @Override
    public void updateBatch(List<Room> rooms) {
        baseMapper.updateBatch(rooms);
    }

    @Override
    public List<Room> financeRankYesterday() {
        List<Room> rooms = getBaseMapper().financeRankYesterday();
        rooms.forEach( li -> {
            User user =userService.getById(li.getUserId());
            if (user != null){
                li.setImg(user.getImg());
            }
            li.setMood(li.getMood()+li.getFixationMood()+li.getPeopleMood());

            //设置主持人
            List<RoomUserWheat>  userWheats=roomUserWheatService.list(new QueryWrapper<RoomUserWheat>().eq("room_id",li.getId()).eq("room_wheat",1));
            if (userWheats!=null) {
                userWheats.forEach(userWheat->{
                    User zc = userService.getById(userWheat.getUserId());
                    userWheat.setUserName(zc.getName());
                    userWheat.setUserImg(zc.getImg());
                    userWheat.setUserSex(zc.getSex());
                });
            }
            li.setUserWheats(userWheats);

            //标签
            if (li.getTagId()!=null) {
                RoomTag roomTag = roomTagService.getById(li.getTagId());
                if (roomTag!=null) {
                    li.setTagImage(roomTag.getImage());
                }
            }
        });
        return rooms;
    }
}
